<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { mdiAccount, mdiClose, mdiContentCopy, mdiEye, mdiEyeOff, mdiKey, mdiWeb } from '@mdi/js'
import { usePasswordManagerStore } from '@/stores/passwordManager'
import { notifyError, notifySuccess } from '@/utils/notify'

const props = defineProps<{ data: F2.user.WebCredential }>()
const emit = defineEmits<{
  (e: 'save', payload: F2.user.WebCredential): void
  (e: 'update', payload: F2.user.WebCredential): void
  (e: 'cancel', clear?: boolean): void
  (e: 'never', domain: string): void
  (e: 'copy', field: 'username' | 'password'): void
}>()

const { t } = useI18n()

const showPassword = ref(true)

// 可编辑本地副本，避免直接修改 props
const username = ref(props.data?.username || '')
const password = ref(props.data?.password || '')

// 当 props.data 变更时同步本地副本
watch(
  () => props.data,
  val => {
    username.value = val?.username || ''
    password.value = val?.password || ''
  },
  { immediate: true }
)

const isUpdate = computed(() => !!props.data?.credentialId)
const actionLabel = computed(() =>
  t(isUpdate.value ? 'savePass.actions.update' : 'savePass.actions.save')
)
const title = computed(() => t(isUpdate.value ? 'savePass.titles.update' : 'savePass.titles.save'))

const domainText = computed(() => {
  if (props.data?.domain) return props.data.domain
  try {
    return new URL(props.data?.url || '').hostname
  } catch {
    return ''
  }
})

const siteTitle = computed(
  () => props.data?.site_name || domainText.value || t('savePass.siteDefault')
)

function buildPayload(): F2.user.WebCredential {
  return { ...props.data, username: username.value, password: password.value }
}

async function onPrimary() {
  /* if (isUpdate.value) emit('update', buildPayload())
  else emit('save', buildPayload()) */
  try {
    const d = buildPayload()
    // 保存密码
    if (isUpdate.value) {
      await usePasswordManagerStore().updateCredential(d)
    } else {
      await usePasswordManagerStore().addCredential(d)
    }
    notifySuccess(t('savePass.toast.saved'), t('savePass.toast.successTitle'), {
      position: 'bottom-center'
    })
    emit('cancel', true)
  } catch (error) {
    const msg = error instanceof Error ? error.message : t('savePass.toast.unknownError')
    notifyError(t('savePass.toast.saveFailed', { message: msg }), t('savePass.toast.errorTitle'), {
      position: 'bottom-center'
    })
  }
}

function copyText(val: string, field: 'username' | 'password') {
  if (!val) return
  try {
    navigator.clipboard?.writeText(val)
  } catch {}
  emit('copy', field)
}
</script>

<template>
  <v-card class="f2-save-pass pa-3" elevation="8">
    <div class="d-flex align-center">
      <v-avatar class="mr-2" size="28">
        <v-img v-if="props.data.favicon_url" cover eager :src="props.data.favicon_url" />
        <v-icon v-else :icon="mdiWeb" size="20" />
      </v-avatar>
      <div class="flex-1 min-w-0">
        <div class="text-body-2 font-weight-medium text-truncate">
          {{ title }} · {{ siteTitle }}
        </div>
        <div class="text-caption text-medium-emphasis text-truncate">{{ domainText }}</div>
      </div>
      <v-btn density="comfortable" icon variant="text" @click="emit('cancel')">
        <v-icon :icon="mdiClose" size="18" />
      </v-btn>
    </div>

    <v-divider class="my-3" />

    <v-text-field
      v-model="username"
      class="mb-2"
      density="compact"
      hide-details="auto"
      :label="t('savePass.fields.username')"
      :prepend-inner-icon="mdiAccount"
      variant="outlined"
    >
      <template #append-inner>
        <v-btn size="x-small" variant="text" @click.stop="copyText(username, 'username')">
          <v-icon :icon="mdiContentCopy" size="16" />
        </v-btn>
      </template>
    </v-text-field>

    <v-text-field
      v-model="password"
      density="compact"
      hide-details="auto"
      :label="t('savePass.fields.password')"
      :prepend-inner-icon="mdiKey"
      :type="showPassword ? 'text' : 'password'"
      variant="outlined"
    >
      <template #append-inner>
        <v-btn size="x-small" variant="text" @click.stop="showPassword = !showPassword">
          <v-icon :icon="showPassword ? mdiEyeOff : mdiEye" size="16" />
        </v-btn>
        <v-btn size="x-small" variant="text" @click.stop="copyText(password, 'password')">
          <v-icon :icon="mdiContentCopy" size="16" />
        </v-btn>
      </template>
    </v-text-field>

    <div class="d-flex justify-end mt-4">
      <v-btn class="mr-1" variant="text" @click="emit('cancel')">
        {{ t('savePass.actions.later') }}</v-btn
      >
      <!--      <v-btn class="mr-2" color="secondary" variant="text" @click="emit('never', domainText)">
        不再提示
      </v-btn>-->
      <v-btn color="primary" @click="onPrimary"> {{ actionLabel }}</v-btn>
    </div>
  </v-card>
</template>

<style scoped>
.f2-save-pass {
  min-width: 320px;
  max-width: 420px;
}
</style>

<i18n>
{
  "zhHans": {
    "savePass": {
      "titles": {
        "save": "保存密码",
        "update": "更新密码"
      },
      "actions": {
        "save": "保存",
        "update": "更新",
        "later": "稍后",
        "never": "不再提示"
      },
      "fields": {
        "username": "用户名",
        "password": "密码"
      },
      "siteDefault": "网站",
      "toast": {
        "saved": "密码已保存",
        "successTitle": "提示",
        "saveFailed": "保存密码失败：{message}",
        "errorTitle": "错误",
        "unknownError": "未知错误"
      }
    }
  },
  "en": {
    "savePass": {
      "titles": {
        "save": "Save Password",
        "update": "Update Password"
      },
      "actions": {
        "save": "Save",
        "update": "Update",
        "later": "Later",
        "never": "Don't ask again"
      },
      "fields": {
        "username": "Username",
        "password": "Password"
      },
      "siteDefault": "Website",
      "toast": {
        "saved": "Password saved",
        "successTitle": "Notice",
        "saveFailed": "Failed to save password: {message}",
        "errorTitle": "Error",
        "unknownError": "Unknown error"
      }
    }
  }
}
</i18n>
